package nancal.mp.service

import nancal.mp.db.mongo.mor
import nbcp.base.extend.scopes
import nbcp.base.utils.SpringUtil
import nbcp.mvc.HttpContext
import nbcp.mvc.sys.LoginUser
import nbcp.myoql.db.comm.EventResult
import nbcp.myoql.db.mongo.MongoBaseQueryClip
import nbcp.myoql.db.mongo.event.IMongoEntityQuery
import nbcp.myoql.db.mongo.query
import org.springframework.stereotype.Component

@Component
class MongoProductLineQueryEvent : IMongoEntityQuery {
    override fun beforeQuery(query: MongoBaseQueryClip): EventResult {
        if (HttpContext.hasRequest == false || SpringUtil.runningInTest) {
            return EventResult(true);
        }

        if (HttpContext.request.LoginUser.isAdmin) {
            return EventResult(true);
        }

        if (scopes.getLatest(NoFilterProductLineScope::class.java) != null) {
            return return EventResult(true);
        }
        if (query.defEntityName == mor.dev.productLine.userDefineTableName) {

            var myUserId = HttpContext.request.LoginUser.id;
            var query2 = mor.dev.productLine.query()
                    .linkOr(
                            { it.leader.id mongoEquals myUserId },
                            { it.pm.id mongoEquals myUserId },
                            { it.lm.id mongoEquals myUserId },
                            {
                                it.developers.id mongoEquals myUserId
                            })

            query.whereData.addAll(query2.whereData)
        }


        return EventResult(true);
    }

    override fun query(query: MongoBaseQueryClip, eventData: EventResult) {

    }
}